import React, { useCallback, useEffect } from 'react';
import { Form, Modal, Input } from 'antd';
import { ICommonModalRefObject, useEnhanceModalRef } from '@/hooks/useModalRef';
import { INode } from '../type';

type IFormData = Pick<INode, 'id' | 'name'>;

export default (props: {
  modalRef: React.MutableRefObject<ICommonModalRefObject>;
}) => {
  const { modalRef } = props;
  const { visible, data, close } = useEnhanceModalRef<{
    type: 'add' | 'edit';
    record?: INode;
    onSuccess?: (data: IFormData) => void;
  }>(modalRef);

  const { type, record, onSuccess } = data || { type: 'add' };
  const [formInstance] = Form.useForm();

  useEffect(() => {
    if (record) {
      formInstance.setFieldsValue(record);
    } else {
      formInstance.resetFields();
    }
  }, [formInstance, record]);

  const onOK = useCallback(async () => {
    const data = await formInstance.validateFields();
    onSuccess?.(data);
    close();
  }, [close, formInstance, onSuccess]);

  return (
    <Modal
      open={visible}
      title={type === 'add' ? '新增' : '编辑'}
      onCancel={close}
      onOk={onOK}
    >
      <Form form={formInstance} labelAlign="right" labelCol={{ span: 4 }}>
        <Form.Item name="id" label="ID" required rules={[{ required: true }]}>
          <Input disabled />
        </Form.Item>
        <Form.Item
          name="name"
          label="Name"
          required
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};
